function inits() {
    var queryUrl = '../devRepairRecord/list';
    var queryArray = [];
    // var delFlag = vm.q.delFlag
    // queryArray.push('delFlag='+ delFlag)
    // 拼接外界可能传入的repairRecord
    var repairCode = getQueryString('repairCode')
    if (repairCode) {
        vm.q.repairCode = 'REP-' + repairCode
        queryArray.push("repairCode=" + vm.q.repairCode);
    }
    //拼接外面可能传入的devId
    var devId = getQueryString('devId');
    if(devId){
        queryArray.push('devId='+devId)
    }
    // 拼接外界可能传入的repairRecord
    var id = getQueryString('Id');
    if (id) {
        queryArray.push("id=" + id);
    }
    if(queryArray.length > 0){
        queryUrl += '?' + queryArray.join('&');
    }
    var grid_selector = '#jqGrid';
    $(grid_selector).Grid({
        url: queryUrl,
        colModel: [
            {label: '产线', name: 'devProductName', index: 'DEV_PRODUCT_NAME', width: 100},
            {label: '设备编码', name: 'devCode', index: 'DEV_CODE', width: 70},
            {label: '设备名称', name: 'devName', index: 'DEV_NAME', width: 100},
            {label: '工单编号', name: 'repairCode', index: 'REPAIR_CODE', width: 90},
            {
                label: '来源', name: 'source', index: 'SOURCE', width: 45,
                formatter: function (value, col, row) {
                    return sysEnums.TICKET_SOURCE[value];
                }
            },
            {label: '报修时间', name: 'uploadDate', index: 'UPLOAD_DATE', width: 90},
            {label: '维修开始时间', name: 'repairStartDate', index: 'REPAIR_START_DATE', width: 90},
            {label: '维修结束时间', name: 'repairEndDate', index: 'REPAIR_END_DATE', width: 90},
            {
                label: '报警信息', sortable: false,
                formatter: function (value, col, row) {
                    if (row.faultCode && row.faultDesc) {
                        return row.faultCode + '(' + row.faultDesc + ")";
                    } else {
                        return '未设置';
                    }
                }
            },
            {label: '时长', name: 'duration', width: 40, sortable: false},
            {label: '维修人', name: 'repairUsername', index: 'REPAIR_USER', width: 40},
            {
                label: '工单状态', width: 45, index: 'DEV_STATUS',
                formatter: function (value, col, row) {
                    return sysEnums.REPAIR_TICKET_STATUS[row.devStatus];
                }, frozen: true,
                cellattr:function (value, options, row) {
                    if(row.delFlag == 0){
                        return "";
                    }else{
                        if(row.devStatus == 1){
                            return "";
                        }else if(row.devStatus == 4){
                            return "style='background-color:rgba(0, 170, 255,0.3);'";
                        }else if(row.devStatus == 6){
                            return "style='background-color:rgba(0, 170, 0,0.3);";
                        }
                    }
                }
            },
            {label: '工单状态', name: 'devStatus', hidden: true},
            {label: '原维修记录ID', name: 'originRepairRecordId', hidden: true},
            {label: '工单状态', name: 'devStatus', hidden: true},
            {label: '设备类型', name: 'devKind', hidden: true},
            {label: '是否异常', name: 'isError', hidden: true},
            {label: '是否删除', name: 'delFlag', hidden: true},
            {label: 'id', name: 'id', index: 'ID', key: true, hidden: true}
        ],
        loadComplete:function (data){
            vm.responseTime  = data.page.userData.total;
        },
        gridComplete: function () {
            // 对于已超期的维修工单行背景渲染为红色
            var ids = $('#jqGrid').getDataIDs();
            for (var i = 0; i < ids.length; i++) {
                var rowData = $('#jqGrid').getRowData(ids[i]);
                if(rowData.delFlag == 0) {
                    $('#' + ids[i]).find("td").addClass("delCss");
                }else{
                    if (rowData.isError == 1) {
                        $('#' + ids[i]).find("td").addClass("urgeCss");
                    }
                }
            };
            var start  = $("#jqGrid").getGridParam("page");
            var rowNum =  $("#jqGrid").getGridParam("rowNum");
            var end  =start*rowNum;
            var begin = '';
            if(start=='1'){
                begin = start
            }else{
                begin = (start-1)*rowNum
            }
            var totalRecords = $("#jqGrid").getGridParam("records");
            setTimeout(function (){
                var customTotalText =begin+' - '+end+ " 共 " + totalRecords + " 条, " + vm.responseTime +' 分钟 ';  // 自定义的总数信息文本
                $(".ui-paging-info").text(customTotalText);
            },50)
        },
        postData: {
            'delFlag': vm.q.delFlag
        }
    });
    /*加载设备组织数*/
    vm.getTreeList();
}

$(function () {
    var ids = getQueryString("id");
    if (ids != null) {
        vm.showList = false;
        vm.add();
        //根据id查询维修工单信息
        Ajax.request({
            url: "../devmaintenwork/info/" + ids,
            async: false,
            successCallback: function (r) {
                vm.devMaintenRepair.devId = r.devMaintenWork.devId
                vm.devMaintenRepair.devName = r.devMaintenWork.devName;
            }
        })
    } else {
        vm.showList = true;
        inits();
        // 初始化表单页用到的设备故障类型树
        vm.getFaultTypeTree();
        //$("#jqGrid").setGridWidth($(window).width());
    }
});

//设备组织树
var deptSetting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "deptId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url: "nourl",
            name: "complexName"
        }
    },
    callback: {
        beforeCheck: true,
        beforeClick: outTreeCheck
    }
};

function outTreeCheck(e, treeObj, treeNode) {


    // vm.query();
}

//给来源筛选框赋值
$(function (){
    let param = sysEnums.TICKET_SOURCE;
    for (const paramKey in param) {
        vm.sourceList.push({
            name:param[paramKey],
            value:paramKey
        })
    }
    console.log( vm.sourceList,'ss')
})
// 表单页用到的设备类型故障树
var formAlarmCategoryTree;
//定义设备报警/故障树配置
var alarmCategoryTreeSetting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "pid",
            rootPId: 0
        },
        key: {
            url: "nourl",
            name: "name" //name 与 typeName 绑定
        },
    }
};

var vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        title: null,
        typeName: "",
        devMaintenRepair: {
            devId: '',
            devCode: '',
            devName: '',
            maintenRecordId: '',
            faultCode: '',
            faultDesc: '',
            vfgId: '',
            cccId: '',
            faultId: '',
            faultCategoryId: '', // 报警分类名称
            faultCategoryName: '', // 报警分类名称
            recordDescr: '',
            reason: '',
            solution: '',
            remark: '',
            id: '',
            startDateTime: '', // Date-Picker组件用
            endDateTime: '', // Date-Picker组件用
            repairStartDate: '',
            repairEndDate: '',
            big: '',//报警分类大类
            middle: '',//报警分类中
            small: ''//报警分类小类
        },
        vrtList: [], // VRT 大类
        vfgList: [], // VFG 种类
        cccList: [], // CCC 小类
        alarmList: [], // 报警代码列表
        flag: '0', //是否新增报警代码新增
        deviceInfoList: {},
        workShopShow: '',//车间显示值
        ticketStatusList: enumsToList('REPAIR_TICKET_STATUS'),
        ticketDelFlagsList:[
            {
                value:'1',
                name:'未删除'
            },
            {
                value:'0',
                name:'已删除'
            }
        ],
        ruleValidate: {
            devId: [
                {required: true, message: '设备编号不能为空', trigger: 'blur'}
            ],
            faultCode: [
                {required: true, type: 'string', message: '报警代码不能为空', trigger: 'change'},
                {
                    trigger: 'blur'
                }
            ],
            faultDesc: [
                {required: true, message: '报警描述不能为空', trigger: 'blur'},
            ],
            startDateTime: [
                {required: true, type: 'date', message: '请选择开始维修时间', trigger: 'change'},
            ],
            endDateTime: [
                {required: true, type: 'date', message: '请选择结束维修时间', trigger: 'change'}
            ],
            recordDescr: [
                {required: true, type: 'string', message: '请输入故障描述', trigger: 'blur'}
            ],
            reason: [
                {required: true, type: 'string', message: '请输入原因分析', trigger: 'blur'}
            ],
            solution: [
                {required: true, type: 'string', message: '请输入解决办法', trigger: 'blur'}
            ]
        },
        repairStartRange: [], // 维修开始查询时间区间
        q: {
            workshopId: '', // 车间ID
            devCode: '', // 设备编码
            devName: '', // 设备名称
            spareName: '', // 备件名称
            spareSpec: '', // 备件规格
            beginTime: '',
            endTime: '',
            devStatus: '',
            repairCode: '', // 维修工单号
            source:'',//来源
            delFlag: '1'//是否删除,0已删除，1未删除
        },
        replaceSpareListCols: [
            {title: '备件编码', key: 'spareCode'},
            {title: '名称', key: 'name'},
            {title: '规格', key: 'spec'},
            {title: '更换数目', key: 'num'}
        ],
        replaceSpareList: [],
        workshopList: [], // 所属车间下拉option列表
        treeList: [],//设备组织树列表
        alarmTypeShow:false,
        sourceList:[],//来源列表
        responseTime:'',//响应时长
        loading2:false,
        searchAlarmList:[],
    },
    created: function () {
        // 加载车间列表
        this.loadWorshopList();
    },
    methods: {
        deptTree: function (param) {
            openWindow({
                title: "请选择设备组织结构",
                area: ['400px', '500px'],
                content: jQuery("#workShopSubmit"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = deptZtree.getSelectedNodes();
                    //设置车间显示值
                    vm.q.devDeptId = node[0].deptId;
                    vm.workShopShow = node[0].complexName;
                    layer.close(index);
                }
            });
        },
        /*加载设备组织树*/
        getTreeList: function () {
            Ajax.request({
                url: '../sys/user/treeDeptBySCX',
                async: false,
                successCallback: function (r) {
                    vm.treeList = r.list;
                    deptZtree = $.fn.zTree.init($("#storeTree"), deptSetting, vm.treeList);
                    // 默认展开工厂一级
                    deptZtree.expandNode(deptZtree.getNodeByParam("deptId", '01', null));
                }
            });
        },
        details: function () {
            var id = getSelectedRow("#jqGrid");
            var record = getSelectedRowData("#jqGrid");
            if (id == null) {
                return;
            }
            openWindow({
                type: 2,
                title: '<i class="fa fa-bars"></i> 维修工单详情',
                content: '../device/devmaintenworkview.html?Id=' + id
            });
        },
        del: function (event) {
            var ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }
            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    url: "../devmaintenwork/delete",
                    params: JSON.stringify(ids),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        report: function () {
            this.assistPersonId = '';
            var id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            var ticket = getSelectedRowData('#jqGrid');
            if(ticket.delFlag==0){
                alert('已删除工单只能查看，不支持其他任意操作！');
                return;
            }

            if (ticket.devStatus != '3') {
                alert('只有处于[维修中]状态的工单才可以申请上一级协助！');
                return;
            }
            let winTitle = '';
            if (ticket.handleNode == '1') {
                winTitle = '请选择车间协助人员';
            } else if (ticket.handleNode == '2') {
                winTitle = '请选择制造处协助人员';
            } else {
                alert('当前工单制造处协助处理中，已达最高级！');
                return;
            }
            let _this = this;
            Ajax.request({
                url: '../devmaintenwork/assistPersonList',
                type: 'POST',
                params: {"id": id},
                async: false,
                successCallback: function (r) {
                    _this.reportPersonList = r.assistPersonList;
                    openWindow({
                        title: winTitle,
                        area: ['400px', '200px'],
                        content: jQuery("#reportPersonList"),
                        btn: ['确定', '取消'],
                        btn1: function (index) {
                            Ajax.request({
                                url: '../devmaintenwork/report',
                                type: 'POST',
                                params: {'id': id, 'assistPersonId': _this.assistPersonId},
                                async: false,
                                successCallback: function (r) {
                                    alert('操作成功', function (index) {
                                        vm.reload();
                                    });
                                }
                            });
                            layer.close(index);
                        }
                    });
                }
            });
        },
        // 维修完成
        completeRepair: function () {
            let ticketId = getSelectedRow('#jqGrid');
            if (!ticketId) {
                return;
            }
            let ticket = getSelectedRowData('#jqGrid');
            console.log(ticket)
            if(ticket.delFlag==0){
                alert('已删除工单只能查看，不支持其他任意操作！');
                return;
            }
            if (ticket.devStatus != '3') {
                alert('只有处于维修中的工单才可以确认完成！');
                return;
            }
            Ajax.request({
                url: '../devmaintenwork/completeRepair',
                params: {"id": ticketId},
                type: 'POST',
                async: false,
                successCallback: function (r) {
                    if (r.over > 0) {
                        alert("操作成功");
                    } else {
                        alert("当前工单已结束，无需重复完成！");
                    }
                    vm.reload();
                }
            });
        },
        //维修人员确定维修工单
        orderSure: function () {

            var ticketId = getSelectedRow("#jqGrid");
            if (ticketId == null) {
                return;
            }
            //工单是否删除
            let ticket = getSelectedRowData('#jqGrid');
            if(ticket.delFlag == 0) {
                alert('已删除工单只能查看，不支持其他任意操作！');
                return;
            }
            //判断当前人员是否已经确定该订单
            Ajax.request({
                url: '../devmaintenwork/orderSure',
                type: 'POST',
                params: {'id': ticketId},
                async: false,
                successCallback: function (r) {
                    if (r.isHas == false) {
                        alert("当前任务已确定");
                    } else {
                        alert("操作成功", function (index) {
                            vm.reload();
                        });
                    }
                }
            })
        },
        handleBeforeUpload: function () {
            this.$refs.uploadFile.clearFiles();
            this.$Loading.start();
        },
        handleSuccess: function (res, file) {
            if (res.code == 0) {
                this.$Loading.finish();
                iview.Message.success('文件上传成功');
                alert(res.msg, function (index) {
                    vm.reload();
                });
            } else {
                this.$Loading.error();
                this.$Notice.error({
                    title: '导入失败',
                    desc: res.msg
                })
            }
        },
        handleError2: function (err, file) {
            alert('导入失败');
        },
        handleFormatError: function (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传.xls或.xlsx的文件。'
            });
        },
        //数据导出
        exportData: function () {
            var queryStringArray = [];
            if (vm.q.beginTime) {
                queryStringArray.push('beginTime=' + gmt2DateStr(vm.q.beginTime));
            }
            if (vm.q.endTime) {
                queryStringArray.push('endTime=' + gmt2DateStr(vm.q.endTime));
            }
            if (vm.q.devName) {
                queryStringArray.push('devName=' + vm.q.devName);
            }
            if (vm.q.devCode) {
                queryStringArray.push('devCode=' + vm.q.devCode);
            }
            if (vm.q.devDeptId) {
                queryStringArray.push('devDeptId=' + vm.q.devDeptId);
            }
            if (vm.q.repairCode) {
                queryStringArray.push('repairCode=' + vm.q.repairCode);
            }
            if (vm.q.devStatus) {
                queryStringArray.push('devStatus=' + vm.q.devStatus);
            }
            var queryString = '';
            if (queryStringArray.length > 0) {
                queryString = '?' + queryStringArray.join('&');
            }
            window.open(encodeURI('../devRepairRecord/export' + queryString));
        },
        // 加载报警代码
        loadAlarmCategory(queryCondition, callback) {
            Ajax.request({
                url: '../alarmcategory/queryAll?' + queryCondition,
                async: true,
                successCallback: data => {
                    if (data.list == 0) {
                        alert('无可选设备报警分类，请等待维护完毕后再进行完善！')
                        return;
                    }
                    callback(data.list);
                }
            });
        },
        /*
               * 1.切换时清空小类 和小类数组
               * 2. 获取小类数组
               * */
        handleVfgChange(vfgOption) {
            if (!vfgOption) {
                return;
            }
            // 清空
            vm.devMaintenRepair.faultCategoryId = '';
            vm.devMaintenRepair.faultCategoryName = '';
            vm.devMaintenRepair.faultId = '';
            vm.devMaintenRepair.faultCode = '';
            vm.devMaintenRepair.faultDesc = '';
            // 清空CCC列表
            this.cccList = [];
            // 清空设备报警代码列表
            this.alarmList = [];
            // 加载CCC列表
            vm.loadAlarmCategory('pid=' + vfgOption, function (dataList) {
                vm.cccList = dataList;
            });
        },
        /*
            报警小类切换时 1.会加载出来报警代码，自动回填
        */
        handleCccChange(cccOption) {
            // 清空设备报警代码库+设备报警西悉尼
            this.devMaintenRepair.faultId = '';
            this.devMaintenRepair.faultCode = '';
            this.devMaintenRepair.faultDesc = '';
            this.alarmList = [];
            // 设置CCCID
            this.devMaintenRepair.faultCategoryId = cccOption;
            this.loadDevAlarmList(cccOption, vm.devMaintenRepair.devId);
        },
        // 加载设备备件代码列表
        loadDevAlarmList(cccId, devId) {
            Ajax.request({
                url: '../alarmcodebase/queryAll?alarmCategoryId=' + cccId + '&devId=' + devId,
                async: true,
                successCallback: data => {
                    this.alarmList = data.list;
                }
            });
        },
        selectAlarmCategory: function () {
            openWindow({
                title: "选择报警/故障分类",
                area: ['400px', '600px'],
                content: jQuery("#faultTypeLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var selectedNodes = formAlarmCategoryTree.getSelectedNodes();
                    if (!selectedNodes || selectedNodes.length == 0) {
                        alert('请选择故障类型！');
                        return;
                    }
                    vm.devMaintenRepair.faultCategoryId = selectedNodes[0].id;
                    vm.devMaintenRepair.faultCategoryName = selectedNodes[0].name;
                    layer.close(index);
                }
            });
        },
        /*
        * 1.报警代码切换
        * */
        showLoc: function (type) {
            if (type == 0) {
                // 手动输入库位
                vm.flag = 1;
                this.$set(this.devMaintenRepair, 'faultCode', '')
            } else if (type == 1) {
                // 从现有库位中选择
                this.$set(this.devMaintenRepair, 'faultCode', '')
                vm.flag = 0;
            }
        },
        loadWorshopList: function () {
            var _this = this;
            Ajax.request({
                url: '../sys/dept/listByDeptLevel?deptLevel=2',
                async: true,
                successCallback: data => {
                    this.workshopList = data.list;
                }
            });
        },
        // 关联备件换件记录
        addReplacePartRecord: function (ticketId, devKind) {
            openWindow({
                type: 2,
                title: '<i class="fa fa-bars"></i> 维修换件记录',
                content: '../spare/sparepartconsumrecord.html?businessId=' + ticketId + '&type=REPAIR'
            })
        },
        getDeviceInfo: function () {
            openWindow({
                type: 2,
                title: '<i class="fa fa-file-text-o"></i> 选择设备',
                content: '../sys/deviceInfoSelect.html',
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var res = iframeWin.getDeviceInfo();
                    if (!res) {
                        iview.Message.error("请选择一条记录");
                    } else {
                        vm.devMaintenRepair.devCode = res.devCode;
                        vm.devMaintenRepair.devName = res.devName;
                        vm.devMaintenRepair.devId = res.id;
                        // 加载报警VRT类
                        vm.loadAlarmCategory('pid=0&categoryCode=' + res.devTypeS, function (vrtList) {
                            vm.devMaintenRepair.vrtId = vrtList[0].id;
                            vm.devMaintenRepair.vrtName = vrtList[0].name;
                            // 继续加载VFG列表
                            vm.loadAlarmCategory('pid=' + vm.devMaintenRepair.vrtId, function (vfgList) {
                                vm.vfgList = vfgList;
                                vm.devMaintenRepair.vfgId = '';
                                vm.devMaintenRepair.faultCategoryId = '';
                                vm.devMaintenRepair.faultCategoryName = '';
                                vm.devMaintenRepair.faultId = '';
                                vm.devMaintenRepair.faultCode = '';
                                vm.devMaintenRepair.faultDesc = '';
                            });
                        });
                        layer.close(index);
                    }
                }
            })
        },
        query: function () {
            vm.reload();
        },
        getFaultTypeTree: function () {
            //加载故障类型树
            Ajax.request({
                url: "../alarmcategory/queryAll",
                async: true,
                successCallback: function (r) {
                    var tree = r.list;
                    formAlarmCategoryTree = $.fn.zTree.init($("#faultTypeTree"), alarmCategoryTreeSetting, tree);
                    // formAlarmCategoryTree.expandNode(faultTree2.getNodeByParam("id", '70', null));
                }
            });
        },
        add: function () {
            vm.showList = false;
            /*
            * 1.清空vfg 和 ccc数组*/
            vm.vfgList = [];
            vm.cccList = [];
            vm.flag = -1;
            vm.loading2 = false,
            vm.searchAlarmList = [],//远程搜索值
            vm.title = "请按照从上到下的顺序，补录设备维修记录";
            vm.devMaintenRepair = {
                devId: '',
                devCode: '',
                devName: '',
                maintenRecordId: '',
                faultCode: '',
                faultDesc: '',
                faultId: '',
                vrtId: '',
                vfgId: '',
                faultCategoryId: '', // 报警分类名称
                faultCategoryName: '', // 报警分类名称
                recordDescr: '',
                reason: '',
                solution: '',
                remark: '',
                id: '',
                startDateTime: '', // Date-Picker组件用
                endDateTime: '', // Date-Picker组件用
                repairStartDate: '',
                repairEndDate: ''
            };
            //查询设备列表
            Ajax.request({
                url: "../deviceinfo/deviceInfoAll",
                async: true,
                successCallback: function (r) {
                    vm.deviceInfoList = r.list;
                }
            })
            vm.getFaultTypeTree();
        },
        remoteMethod2:function (query) {
            const that = this;
            if(query.length<3){
                return
            }
            if(query.indexOf('暂无需要报警代码,手动选择录入')>-1){
                vm.flag='0'
                return;
            }
            var url = '../alarmcodebase/query'+'?devId='+vm.devMaintenRepair.devId+'&alarmCode='+query;
            that.loading2 = true;
            vm.searchAlarmList  =[];
            Ajax.request({
                url: url,
                async: true,
                successCallback: function (r) {
                    that.loading2 = false;
                    let data = r.list;
                    if(r.list.length==0){
                        //暂无需要代码，手动选择
                        that.searchAlarmList.push({
                            value:'000',
                            label:query+'暂无需要报警代码,手动选择录入。'
                        })
                        return
                    }
                    for (let i = 0; i < data.length; i++) {
                        vm.searchAlarmList.push({
                            value:data[i].id,
                            label:data[i].alarmCode+data[i].alarmDesc
                        })
                    }

                }
            });

        },
        update: function (event) {
            var id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";
            Ajax.request({
                url: "../deviceinfo/deviceInfoAll",
                async: false,
                successCallback: function (r) {
                    vm.deviceInfoList = r.list;
                }
            });
            vm.getFaultTypeTree();
            vm.getInfo(id);
        },
        perfectRepairRecord: function () {
            let selectedRowDatas = getSelectedRowDatas("#jqGrid");
            if (selectedRowDatas.length == 0) {
                this.add();
            } else {
                if (selectedRowDatas.length > 1) {
                    alert('最多只能选择一条记录！');
                } else {
                    if(selectedRowDatas[0].delFlag == 0){
                        alert('已删除工单只能查看，不支持其他任意操作！');
                        return;
                    }
                    this.addRepairRecord(selectedRowDatas[0].id);
                }
            }
        },
        // 完善维修记录
        addRepairRecord: function (ticketId) {
            openWindow({
                type: 2,
                area: ['100%', '100%'],
                title: '<i class="fa fa-bars"></i> 完善维修记录',
                content: '../device/perfectRepairRecord.html?id=' + ticketId,//+'&workId'+date.id
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var devRepairRecord = iframeWin.getDateform();
                    if (devRepairRecord.repairStartDate) {
                        devRepairRecord.repairStartDate = gmt2DateTimeStr(devRepairRecord.repairStartDate);
                    }
                    if (devRepairRecord.repairEndDate) {
                        devRepairRecord.repairEndDate = gmt2DateTimeStr(devRepairRecord.repairEndDate);
                    }
                    // if (!devRepairRecord.faultCategoryId) {
                    //     alert('故障分类必选！');
                    //     return;
                    // }
                    if (!devRepairRecord.recordDescr) {
                        alert('故障描述必填！');
                        return;
                    }
                    if (!devRepairRecord.reason) {
                        alert('原因分析必填！');
                        return;
                    }
                    if (!devRepairRecord.solution) {
                        alert('解决方法必填！');
                        return;
                    }
                    for (let i = 0; i <devRepairRecord.preventMeasureList.length ; i++) {
                        if( !devRepairRecord.preventMeasureList[i].startDate || !devRepairRecord.preventMeasureList[i].endDate){
                            alert('措施时间必填！');
                            return;
                        }
                    }
                    if (devRepairRecord.preventMeasureList.length > 0) {
                        for (let i = 0; i < devRepairRecord.preventMeasureList.length; i++) {
                            devRepairRecord.preventMeasureList[i].startDate = (gmt2DateTimeStr(devRepairRecord.preventMeasureList[i].startDate)).substring(0, 16)
                            devRepairRecord.preventMeasureList[i].endDate = (gmt2DateTimeStr(devRepairRecord.preventMeasureList[i].endDate)).substring(0, 16)
                        }
                    }
                    if (!devRepairRecord.attachment) {
                        devRepairRecord.attachment = '';
                    }
                    //当前维修时长已超过8小时，是否确认正确输入维修开始时间和维修结束时间？
                    let starDate = new Date(devRepairRecord.repairStartDate).getTime();
                    let endTime = new Date(devRepairRecord.repairEndDate).getTime();
                    let eight = 8 * 60 * 60 * 1000;
                    if ((endTime - starDate) > eight) {
                        confirm('当前维修时长已超过8小时，是否确认输入正确的维修开始和维修结束时间？', function () {
                            Ajax.request({
                                url: "../devRepairRecord/save",
                                params: JSON.stringify(devRepairRecord),
                                type: "POST",
                                contentType: "application/json",
                                successCallback: function (r) {
                                    if (r.code == 0) {
                                        alert('操作成功', function (index) {
                                            vm.reload();
                                        });
                                        layer.close(index);
                                    }
                                }
                            });
                        })
                    } else {
                        // 获取请求URL
                        Ajax.request({
                            url: "../devRepairRecord/save",
                            params: JSON.stringify(devRepairRecord),
                            type: "POST",
                            contentType: "application/json",
                            successCallback: function (r) {
                                if (r.code == 0) {
                                    alert('操作成功', function (index) {
                                        vm.reload();
                                    });
                                    layer.close(index);
                                }
                            }
                        });
                    }
                }
            });
        },
        saveOrUpdate: function (callback) {
            if (vm.devMaintenRepair.startDateTime) {
                vm.devMaintenRepair.repairStartDate = gmt2DateTimeStr(vm.devMaintenRepair.startDateTime)
            }
            if (vm.devMaintenRepair.endDateTime) {
                vm.devMaintenRepair.repairEndDate = gmt2DateTimeStr(vm.devMaintenRepair.endDateTime)
            }
            var url;
            var isSave = true;
            if (vm.devMaintenRepair.id == (null || '')) {
                url = "../devRepairRecord/addRepairRecord";
            } else {
                url = "../devRepairRecord/update";
                isSave = false;
            }
            let starDate = new Date(vm.devMaintenRepair.repairStartDate).getTime();
            let endTime = new Date(vm.devMaintenRepair.endDateTime).getTime();
            let eight = 8 * 60 * 60 * 1000;
            if ((endTime - starDate) > eight) {
                confirm('当前维修时长已超过8小时，是否确认输入正确的维修开始和维修结束时间？', function () {
                    Ajax.request({
                        url: url,
                        params: JSON.stringify(vm.devMaintenRepair),
                        type: "POST",
                        contentType: "application/json",
                        successCallback: function (r) {
                            alert('操作成功', function (index) {
                                if (isSave) {
                                    vm.showList = true;
                                    vm.addRepairRecord(r.repairRecord.id);
                                } else {
                                    vm.reload();
                                }
                            });
                        }
                    });
                })
            } else {
                Ajax.request({
                    url: url,
                    params: JSON.stringify(vm.devMaintenRepair),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function (r) {
                        alert('操作成功', function (index) {
                            if (isSave) {
                                vm.showList = true;
                                vm.addRepairRecord(r.repairRecord.id);
                            } else {
                                vm.reload();
                            }
                        });
                    }
                });
            }
        },
        del: function (event) {
            var ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }
            let ticket = getSelectedRowData('#jqGrid');
            if(ticket.delFlag == 0) {
                alert('已删除工单只能查看，不支持其他任意操作！');
                return;
            }
            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    url: "../devRepairRecord/delete",
                    params: JSON.stringify(ids),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            layer.closeAll();
                            vm.reload();
                        });
                    }
                });
            });
        },
        // 添加维修记录
        viewRepairDetail: function (ticketId) {
            openWindow({
                type: 2,
                title: '<i class="fa fa-bars"></i> 完善维修记录',
                content: '../device/perfectRepairRecord.html?id=' + ticketId,//+'&workId'+date.id
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var devRepairRecord = iframeWin.getDateform();
                    if (devRepairRecord.repairStartDate) {
                        devRepairRecord.repairStartDate = gmt2DateTimeStr(devRepairRecord.repairStartDate);
                    }
                    if (devRepairRecord.repairEndDate) {
                        devRepairRecord.repairEndDate = gmt2DateTimeStr(devRepairRecord.repairEndDate);
                    }
                    if (!devRepairRecord.faultCategoryId) {
                        alert('设备报警CCC必选！');
                        return;
                    }
                    // 获取请求URL
                    Ajax.request({
                        url: "../devRepairRecord/save",
                        params: JSON.stringify(devRepairRecord),
                        type: "POST",
                        contentType: "application/json",
                        successCallback: function (r) {
                            alert('操作成功', function () {
                                layer.close(index);
                                vm.reload();
                            });
                        }
                    });

                }
            });
        },
        getInfo: function (id) {
            Ajax.request({
                url: "../devRepairRecord/info/" + id,
                async: true,
                successCallback: function (r) {
                    vm.showList = false;
                    vm.title = "维修记录详情";
                    vm.devMaintenRepair = r.devMaintenRepair;
                }
            });
        },
        reload: function (event) {
            vm.showList = true;
            if (this.q.beginTime) {
                this.q.beginTime = gmt2DateStr(this.q.beginTime);
            }
            if (this.q.endTime) {
                this.q.endTime = gmt2DateStr(this.q.endTime);
            }
            // $("#jqGrid").setGridWidth($(window).width());
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: this.q,
                page: page
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
        },
        reloadSearch: function () {
            this.q = {
                workshopId: '',
                devCode: '',
                devName: '', // 设备名称
                spareName: '', // 备件名称
                spareSpec: '', // 备件规格
                beginTime: '',
                endTime: '',
                devStatus: '',
                devDeptId: '',//车间id
                repairCode: '',//维修编号清空
                source:'',
                delFlag:'1',
            };
            this.workShopShow = '';
            this.repairStartRange = [];
            this.reload();
            deptZtree.cancelSelectedNode();
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
        getByDevCode: function (id) {
            if (!id) {
                return;
            }
            Ajax.request({
                url: "../deviceinfo/info/" + id,
                type: 'POST',
                successCallback: function (r) {
                    var deviceInfo = r.deviceInfo;
                    vm.devMaintenRepair.devId = deviceInfo.id;
                    vm.devMaintenRepair.devCode = deviceInfo.devCode;
                    vm.devMaintenRepair.devName = deviceInfo.devName;
                }
            });
        },
        handleRepairStartRangeChange(dateVal, dateType) {
            this.q.beginTime = dateVal[0];
            this.q.endTime = dateVal[1];
        },
        handleBeforeUpload: function () {
            this.$refs.uploadFile.clearFiles();
            this.$Loading.start();
        },
        handleSuccess: function (res, file) {
            if (res.code == 0) {
                this.$Loading.finish();
                iview.Message.success('文件上传成功');
                alert(res.msg, function (index) {
                    vm.reload();
                });
            } else {
                this.$Loading.error();
                this.$Notice.error({
                    title: '导入失败',
                    desc: res.msg
                })
            }
        },
        handleError: function (err, file) {
            alert('导入失败');
        },
        handleFormatError: function (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传.xls或.xlsx的文件。'
            });
        }
    }
});

function getauxiliary(id) {
    var i;
    Ajax.request({
        url: '../devmaintenwork/Auxiliary',
        type: 'POST',
        params: {"id": id},
        async: false,
        successCallback: function (r) {
            i = r.i
        }
    })
    return i;
}
